<link rel="stylesheet" href="/static/cloud/css/cloud.css" />
<style type="text/css">
	.content {
		margin: 20px;
	}

	.content ul {
		padding-top: 10px;
		padding-bottom: 10px
	}

	.content .layui-nav .url {
		padding-right: 0.5rem;
		padding-left: 0.5rem;
		cursor: pointer;
		text-align: center;
		line-height: 40px
	}

	.content .bar {
		margin-bottom: 0.5rem
	}

	.content .layui-nav {
		background: white;
		color: #6d6d6d;
		padding: 0
	}

	.content .table_file_name {
		color: #00986f;
	}

	.content .table_file_name:hover {
		cursor: pointer;
		color: #5fb878;
	}

	.content .forbid {
		color: #cacaca
	}

	.add_box{
		padding: 20px;
	}
</style>
<div class="content">
	<script type="text/html" id="add_new_tpl">
		<div class="add_box">
				<div class="layui-form" lay-filter='add_new_form'>
					<div class="layui-form-item layui-form-text">
						<label class="layui-form-label">下载地址</label>
						<div class="layui-input-block">
							<textarea name="download_url" required lay-verify="required" placeholder="支持BT等"
								class="layui-textarea"></textarea>
						</div>
					</div>

					<!-- <div class="layui-form-item">
						<label class="layui-form-label">目标目录</label>
						<div class="layui-input-block">
							<input type="text" name="path" required lay-verify="required" placeholder="请输入标题" value="/离线下载"
								class="layui-input">
						</div>
					</div> -->

					<div class="layui-form-item">
						<label class="layui-form-label">目标目录</label>
						<div class="layui-input-block">
							<select id="path_list" name="path" lay-verify="required">
							</select>
						</div>
					</div>

					<div class="layui-form-item">
						<label class="layui-form-label">文件名</label>
						<div class="layui-input-block">
								<input type="text" name="file_name" placeholder="（可空）文件名" class="layui-input">
						</div>
					</div>


							<div class="layui-form-item">
								<div class="layui-input-block">
									<button class="layui-btn" lay-submit lay-filter="add_new_submit">开始下载</button>
									<!-- <button type="reset" class="layui-btn layui-btn-primary">重置</button> -->
								</div>
							</div>
						</div>
					</div>
	</script>
	<script type="text/html" id="table-file-name-tpl">
		{{# if(d.delete_time){ }}
	  	<div class="forbid">[已删除] {{d.file_name}}</div>
		{{# }else if(!d.file_id){ }}
		<div class="forbid">[文件已删除]</div>
	  	{{# }else{ }}
	  	<div class="table_file_name" lay-event="title" title="{{d.file_name}}" >{{d.file_name}}</div>
	  	{{# } }}
	</script>
	<script type="text/html" id="table-bar-tpl">
		{{# if(d.delete_time){ }}
		<a class="layui-btn layui-btn-xs layui-btn-disabled" lay-event="">打开所在目录</a>
		{{# }else if(!d.file_id){ }}
		<a class="layui-btn layui-btn-xs layui-btn-disabled" lay-event="">打开所在目录</a>
		{{# }else{ }}
		<a class="layui-btn layui-btn-xs layui-btn-primary layui-border-blue" lay-event="open">打开所在目录</a>
		{{# } }}
	  	
	  	<a class="layui-btn layui-btn-xs layui-btn-primary layui-border-red" lay-event="del" data-id={{d.id}}>取消收藏</a>
	</script>
	<script type="text/html" id="table-bar-image">
		{{# if(d.type==2){ }}
			<img style="width: 1.5rem" src="/static/layui_extends/fileManager/img/dir.png">
	  	{{# }else if(d.type==1){  }}
	  		<img style="width: 1.5rem" src="/static/layui_extends/fileManager/img/{{app.getExtendName(d.file_name)}}.png" onerror="this.src='/static/layui_extends/fileManager/img/none.png'">
	  	{{# }else{ }}
	  		<img style="width: 1.5rem" src="/static/layui_extends/fileManager/img/none.png">
	  	{{# } }}
	</script>
	<!-- 回收站列表工具模板 -->
	<script type="text/html" id="table-bar-tpl-recycle">
	  	<a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="recycle_recover" data-id={{d.id}}>恢复</a>
		<a class="layui-btn layui-btn-xs layui-btn-primary layui-border-red " lay-event="recycle_del" data-id={{d.id}}>永久删除</a>
	</script>
	<div class="layui-row layui-col-space20">
		<!-- <div class="layui-col-md2"> -->
		<div class="cloud-card bar">
			<ul class="layui-nav">
				<li class="layui-nav-item" data-id='1'>
					<div class="url" data-href='/index/offinedownload_list?type=1'>正在下载</div>
				</li>
				<li class="layui-nav-item" data-id='2'>
					<div class="url" data-href='/index/offinedownload_list?type=2'>下载完成</div>
				</li>
				
			</ul>
		</div>
		<!-- </div> -->
		<!-- <div class="layui-col-md10"> -->
		<div class="cloud-card table">
			<button class="layui-btn add_new">+ 添加</button>
			
			
			<table class="layui-table">
				<colgroup>
					<col width="150">
					<col>
					<col>
				</colgroup>
				<thead>
					<tr>
						<th>文件名</th>
						<th>已下载/大小</th>
						<th>百分比</th>
						<!-- <th>当前速度</th> -->
						<th>状态</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody class="offine-download-content">
					<!-- 列表 -->
				</tbody>
			</table>
			<!-- <table class="layui-hide" id="data-table" lay-filter="data-table"></table> -->
		</div>
		<!-- </div> -->
	</div>
</div>
<script type="text/javascript">
	layui.use(['table','element','layer','form'], function () {
		var table = layui.table, $ = layui.$,layer=layui.layer, form = layui.form;

		var type = app.parseUrl().params.type || 1;
		var url = ['/api/index/getCollectList', '/api/index/getUploadList', '', '/api/recycle/getList.html']
		
		// element.render('progress', 'filter');
		app.setTopMenu('/index/file');
		$('.content .layui-nav .url').click(function () {
			app.go($(this).attr('data-href'));
		})

		// 设置页面标题
		var title = "";
		if (!type) {
			title = $('.content .layui-nav-item[data-id=' + 1 + '] div').text();
		} else {
			title = $('.content .layui-nav-item[data-id=' + type + '] div').text();
		}
		$("title").text(title + ' - 离线下载 - 私有云盘');

		$('.content .layui-nav-item[data-id=' + type + '] div').addClass('layui-this')
		var cols = [];
		if (!app.isMobile()) {
			cols.push({ field: '', title: '图标', toolbar: '#table-bar-image', width: 80, align: 'center' });
			if (type == 1) {
				cols.push({ field: 'file_name', title: '文件名', toolbar: "#table-file-name-tpl" });
				cols.push({ field: 'time', title: '收藏时间' });
				cols.push({ field: 'size', title: '尺寸' });
				cols.push({ field: 'finish_size', title: '尺寸' });
				cols.push({ title: '操作', toolbar: '#table-bar-tpl', align: 'center' });
			} else if (type == 2) {
				cols.push({ field: 'file_name', title: '文件名', toolbar: "#table-file-name-tpl" });
				cols.push({ field: 'create_time', title: '上传时间' });
			}

		}

		app.ajaxPost('/api/aria2/getList', {},function (res) {
			console.log(res)
			// layer.msg('已清除')
			// location.reload()
			var status_text=['已暂停','等待','正在下载',"已完成",'下载错误:'];
			var err_msg='';
			
			for (let index = 0; index < res.data.length; index++) {
				const element = res.data[index];
				// console.log(res.data.list[index])
				// var control_btn_title = element.status == 1 ? "继续" : "暂停";
				var status_title= status_text[element.status - 1];
				// var percent= (element.finish_size/element.size*100).toFixed(2);//保留两位
				
				var html = '<tr id="download_'+ element.only_tag+'" data-status="'+ element.status +'"><td>'+ element.file_name+'</td>'
					+ "<td id='size_title_" + element.only_tag +"'>--/--</td>"
					+ "<td id='percent_title_" + element.only_tag +"'>0%</td>"
					// + "<td id='current_speed_title_"+ element.only_tag+"'>" + app.bytesToSize(element.current_speed)+"</td>"
					+ "<td id='status_title_"+ element.only_tag+"'>" + status_title+"</td>"
					+ "<td><button class='layui-btn layui-btn-xs' id='control_btn_"+ element.only_tag+"'>--</button><button id='del_btn_" + element.only_tag +"' class='layui-btn layui-btn-xs'>删除</button></td></tr>";
				$(".offine-download-content").append(html);
				var need_interval_status=['1','2','3'];//需要创建定时器的状态
				if(element.status==1 || element.status == 2 || element.status == 3){
					// 开启定时
					create_timer(element.only_tag);
				}

				update_download_param(element.only_tag, element.size, element.finish_size,null, element.status)
				
				
				// 控制按钮 暂停/开始
				$('#control_btn_'+ element.only_tag).click(function(){
					// $(this).parent().parent().data('status')
					var status= $('#download_' + element.only_tag).data('status');
					var p_data={};
					p_data['gid'] = element.only_tag;
					if(status==1){
						// ==============
						// == 继续下载 ==
						// ==============
						$('#control_btn_' + element.only_tag).text('暂停');
						$('#download_' + element.only_tag).data('status',2);
						// $('#status_title_' + element.only_tag).text("正在下载");
						app.ajaxPost("/api/aria2/continue",p_data,function(res){
							console.log(res);
						})
						create_timer(element.only_tag);
					}else if(status == 5){
						// ==============
						// == 下载出错 ==
						// ==============
						$('#control_btn_' + element.only_tag).text('重新下载');
					}else{
						// ==============
						// == 暂停下载 ==
						// ==============
						$('#control_btn_' + element.only_tag).text('继续');
						$('#download_' + element.only_tag).data('status',1);
						// $('#status_title_' + element.only_tag).text("已暂停");
						
						app.ajaxPost("/api/aria2/stop",p_data,function(res){
							console.log(res);
						})
					}
				})

				// 删除按钮
				$('#del_btn_' + element.only_tag).click(function () {
					console.log('删除项目', element.only_tag);
					var p_data = {};
					p_data['gid'] = element.only_tag;
					app.ajaxPost("/api/aria2/delete", p_data, function (res) {
						console.log(res);
					})
				})
			}
			
		});

		// 更新下载项参数
		function update_download_param(only_tag,size,finish_size,current_speed,status){
			if(size){
				$('#size_title_' + only_tag).text(app.bytesToSize(finish_size) + "/" + app.bytesToSize(size)); 
				$('#percent_title_' + only_tag).text((finish_size / size * 100).toFixed(2)+'%');
			}
			if(current_speed){
				$('#current_speed_title_' + only_tag).text(app.bytesToSize(current_speed));
			}
			// 状态
			if(status){
				if(status==4 || status==7 || status==8){
					$('#control_btn_'+ only_tag).hide()
				}else if(status == 1){
					$('#control_btn_'+ only_tag).text('继续')
				}else if(status==1 || status == 2 || status == 3 ){
					$('#control_btn_'+ only_tag).text('暂停')
				}else if(status==5){
					$('#control_btn_'+ only_tag).text('重新下载')	
				}
				var status_title=['已暂停','等待下载','下载中','下载完成','下载错误','下载已删除','转存中','转存完成','转存失败']
				$('#status_title_' + only_tag).text(status_title[status-1]);
			}
		}

		function create_timer(only_tag){
			console.log('创建定时器-', only_tag);
			var timmerId=setInterval(function () {
				app.ajaxPost("/api/aria2/getOne", { only_tag:only_tag }, function (res) {
					console.log(res);
					update_download_param(res.data.only_tag, res.data.size, res.data.finish_size, null, res.data.status)
					if(res.data.status == 1 || res.data.status == 4 || res.data.status == 5 ){
						console.log('停止定时器-', only_tag);
						clearInterval(timmerId);
					}
					
				})
			}, 3000);
		}

		$('.add_new').click(function(){
			const layer_index=layer.open({
				type: 1,
				title:"添加离线下载",
				// skin: 'layui-layer-rim', //加上边框
				area: ['420px', '380px'], //宽高
				content: $('#add_new_tpl').html(),
				success:function(index){
					app.ajaxPost("/api/aria2/getPathList",{}, function (res) {
						console.log(res);
						for (let i = 0; i < res.data.length; i++) {
							const element = res.data[i];
							var path='';
							if(element.path=='/'){
								path= element.path+ element.file_name;
							}else{
								path= element.path+ '/' +element.file_name;
							}
							$('#path_list').append('<option value="' + path+'">'+ path+'</option>');
						}
						form.render();
					})
					form.on('submit(add_new_submit)', function (data) {
						console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
						console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
						console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
						
						app.ajaxPost("/api/aria2/new", data.field, function (res) {
							if (res.err_code==0){
								console.log(res);
								location.reload();
							}else{
								layer.msg(res.err_msg)
							}
						})
						return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
					});
					// p_data
					
				}
			});
		})

		// $('#clean_log_btn').click(function () {
		// 	if (type == 1) {
		// 		layer.confirm('确定清空所有收藏？', {
		// 			btn: ['确定', '取消'] //按钮
		// 		}, function () {
		// 			app.ajaxPost('/api/file/delCollect', { file_id: 0, all: 1 }, function () {
		// 				layer.msg('取消成功')
		// 				location.reload()
		// 			});
		// 		})

		// 	} else if (type == 2) {

		// 		layer.confirm('确定清空所有上传记录？', {
		// 			btn: ['确定', '取消'] //按钮
		// 		}, function () {
					        
		// 		})
		// 	} else if (type == 3) {
		// 		app.runTpl('file_tool', { file_id: 4, elem: '.table' })
		// 	}

		// })
	})
</script>